package com.example.application.views.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.server.VaadinSession;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MyHttpClientUtil {

    private MyHttpClientUtil(){

    }

    /**
     * get请求，自己拼url
     * @param url 请求的地址
     * @param encode 响应结果编码的格式，为null值时默认是utf-8
     * @return  响应的json字符串
     */
    public static String HttpGet(String url,String encode){
        String content = null;
        if(encode == null){
            encode = "utf-8";
        }
        try(CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build()) {
            HttpGet httpGet = new HttpGet(url);
            try(CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpGet)) {
                HttpEntity entity = httpResponse.getEntity();
                content = EntityUtils.toString(entity, encode);
            }catch (Exception e){
                e.printStackTrace();
            }
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return content;
    }

    /**
     *post请求
     * @param url 请求的路径
     * @param map 请求参数集合，没有时直接设置为null
     * @param encode  响应结果编码的格式，为null值时默认是utf-8
     * @return  响应的json字符串
     */
    public static String httpPost(String url, Map<String,String> map, String encode){
        String content = null;
        if(encode == null){
            encode = "utf-8";
        }
        try(CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build()) {
            HttpPost httpost = new HttpPost(url);
            if(map!=null) {
                List<NameValuePair> nvps = new ArrayList<>();
                Set<String> key = map.keySet();
                for (String s : key) {
                    nvps.add(new BasicNameValuePair(s, map.get(s)));
                }
                httpost.setEntity(new UrlEncodedFormEntity(nvps));
            }
            try(CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpost)) {
                HttpEntity entity = httpResponse.getEntity();
                content = EntityUtils.toString(entity, encode);
            }catch (Exception e){
                e.printStackTrace();
            }
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return content;
    }

    /**
     *put请求
     * @param url 请求的路径
     * @param map 请求参数集合，没有时直接设置为null
     * @param encode  响应结果编码的格式，为null值时默认是utf-8
     * @return  响应的json字符串
     */
    public static String httpPut(String url, Map<String,String> map, String encode){
        String content = null;
        if(encode == null){
            encode = "utf-8";
        }
        try(CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build()) {
            HttpPut httput = new HttpPut(url);
            if(map!=null) {
                List<NameValuePair> nvps = new ArrayList<>();
                Set<String> key = map.keySet();
                for (String s : key) {
                    nvps.add(new BasicNameValuePair(s, map.get(s)));
                }
                httput.setEntity(new UrlEncodedFormEntity(nvps));
            }
            try(CloseableHttpResponse httpResponse = closeableHttpClient.execute(httput)) {
                HttpEntity entity = httpResponse.getEntity();
                content = EntityUtils.toString(entity, encode);
            }catch (Exception e){
                e.printStackTrace();
            }
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return content;
    }

    /**
     *delete请求
     * @param url 请求的路径
     * @param id 请求参数集合，没有时直接设置为null
     * @param encode  响应结果编码的格式，为null值时默认是utf-8
     * @return  响应的json字符串
     */
    public static String httpDelete(String url, int id, String encode){
        String content = null;
        if(encode == null){
            encode = "utf-8";
        }
        try(CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build()) {
            HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url + "/" + id);

            CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpDelete);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return content;
    }

    /**
     *post请求
     * @param url 请求的路径
     * @param userBean 请求参数集合，没有时直接设置为null
     * @param encode  响应结果编码的格式，为null值时默认是utf-8
     * @return  响应的json字符串
     */
    public static String httpPost(String url, Object userBean, String encode){
        String content = null;
        if(encode == null){
            encode = "utf-8";
        }
        CloseableHttpResponse httpResponse = null;
        try(CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build()) {
            HttpPost httpPost = new HttpPost(url);

            ObjectMapper objectMapper = new ObjectMapper();

            String jsonSting = objectMapper.writeValueAsString(userBean);
//            System.out.println(jsonSting);

            StringEntity entity = new StringEntity(jsonSting,encode);
//            System.out.println(entity);
            httpPost.setHeader("Content-Type", "application/json;charset=utf8");
            httpPost.setEntity(entity);

            httpResponse = closeableHttpClient.execute(httpPost);
            // 由客户端执行(发送)Post请求
            HttpEntity responseEntity = httpResponse.getEntity();
            content = EntityUtils.toString(responseEntity,encode);
//            System.out.println(content);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                httpResponse.close();
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }

        System.out.println(content);
        return content;
    }

    public static String httpPut(String url, Object providerBean, String encode){
        String content = null;
        CloseableHttpResponse httpResponse=null;
        if(encode == null){
            encode = "utf-8";
        }
        try(CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build()) {
            HttpPut httput = new HttpPut(url);
            //转成json
            ObjectMapper objectMapper = new ObjectMapper();
            //前端的json
            String jsonSting = objectMapper.writeValueAsString(providerBean);
            StringEntity entity = new StringEntity(jsonSting,encode);
            httput.setHeader("Content-Type", "application/json;charset=utf8");
            httput.setEntity(entity);
            httpResponse =  closeableHttpClient.execute(httput);
            // 由客户端执行(发送)Put请求
            HttpEntity responseEntity = httpResponse.getEntity();
            //接受后台返回的字符串
            content = EntityUtils.toString(responseEntity,encode);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                httpResponse.close();
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }

        return content;
    }

    public static void addSession(CloseableHttpResponse response){
        Header[] headers = response.getHeaders("Set-Cookie");
        VaadinSession session = UI.getCurrent().getSession();
        if (headers != null) {
            for (Header header : headers) {
                if(header.getValue().startsWith("JSESSIONID")){
                    String[] vals = header.getValue().split("=");
                    session.setAttribute(vals[0],vals[1]);
                }
            }
        }
    }

    public static void setSession(HttpRequestBase httpRequestBase){
        VaadinSession session = UI.getCurrent().getSession();
        Object jsessionId = session.getAttribute("JSESSIONID");
        System.out.println(jsessionId);
        if (jsessionId != null){
            httpRequestBase.setHeader("Cookie", "JSESSIONID=" + (String) jsessionId);
        }
    }

}
